# coding:utf8  --解决中文编码问题
import re

fileName = "C:\\test.txt"

# 读取文件内容, 最后关闭文件
file1 = open(fileName)
print "读取文件内容:", file1.read()
file1.close()

# 用file类读取文件内容
file2 = file(fileName)
print "用file类读取文件内容:", file2.read()
file2.close()

# 用with方式，会自动帮我们调用close方法
with open(fileName) as f:
    print "用with方式读取文件内容:", f.read()

# 往文件写入内容, w模式会创建并覆盖原有文件, r+模式从光标所在位置开始写入(避免覆盖原有内容，需先调用readlines方法)
fileNameNew = 'new.txt'
fileNew = open(fileNameNew, 'w+')
fileNew.write('hi, new python file!')
fileNew.flush()
fileNew.seek(0, 0)
print "读取新文件内容:", fileNew.read()
fileNew.close()

# a+模式写入内容会以追加方式写入
with open(fileNameNew, 'a+') as fileNew:
    fileNew.write('\nNice to meet you.')
    fileNew.flush()
    fileNew.seek(0, 0)
    print "以a+模式写入后:", fileNew.read()

# r+模式写入内容会从文件头开始覆盖原有内容, 若要追加在最后，则需先调用readlines
with open(fileNameNew, 'r+') as fileNew:
    fileNew.write('python')
    fileNew.flush()
    fileNew.seek(0, 0)
    print "以r+模式直接写入:", fileNew.read()
    fileNew.readlines()
    fileNew.write('python')
    fileNew.flush()
    fileNew.seek(0, 0)
    print "以r+模式readlines后写入:", fileNew.read()


# 按行读取
with open(fileNameNew) as fileNew:
    print "按行读取:"
    for line in fileNew.readlines():
        print line

# 同时写入多行内容
lines = ['\npython is esay', '\ntwo girls is dancing', '\nwelcome to python']
with open(fileNameNew, 'a+') as fileNew:
    fileNew.writelines(lines)
    fileNew.seek(0, 0)
    print "同时写入多行:", fileNew.read()

# 查找文件内容
sizes = 0
with open(fileNameNew) as fileNew:
    for line in fileNew.readlines():
        sizes += len(re.findall('python', line))
print "文件内含python的个数:", sizes

# 替换文件内容
content = ''
with open(fileNameNew) as fileNew:
    content = fileNew.read()
content = re.sub('python', 'JAVA', content)
with open(fileNameNew, 'w+') as fileNew:
    fileNew.write(content)
    fileNew.flush()
    fileNew.seek(0, 0)
    print "python替换成JAVA后:", fileNew.read()